import subprocess, shutil, os,stat
import sys, traceback, time, re
from httplib import HTTPConnection
import urllib, urllib2

debug = 0

def get_pbi(product_ver, pbi_id, headers = None,urlencode = True):
    host = 'pbi.huawei.com:80'
    url = '/pbiws/cxfservices/pbiWebservice'
    if pbi_id == "" and product_ver != "":
        params = '''
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://service.pbiws.it.huawei.com/">
   <soapenv:Header/>
   <soapenv:Body>
      <ser:queryPBIEntitiesNew>
         <param>
            <categoryList>402-00023808</categoryList>
            <categoryList>434-00024708</categoryList>
            <cn>%s</cn>
            <queryType>0</queryType>
            <status>1</status>
         </param>
         <systemId>EulerOS_devops,,,9EDCw0DqAD</systemId>
      </ser:queryPBIEntitiesNew>
   </soapenv:Body>
</soapenv:Envelope>
''' % (product_ver)
    elif pbi_id != "" and product_ver == "":
        params = '''
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://service.pbiws.it.huawei.com/">
   <soapenv:Header/>
   <soapenv:Body>
      <ser:queryPBIEntitiesNew>
         <param>
            <categoryList>402-00023808</categoryList>
            <categoryList>434-00024708</categoryList>
            <id>%s</id>
            <pageIndex>1</pageIndex>
            <pageSize>500</pageSize>
            <status>2</status>
         </param>
         <systemId>EulerOS_devops,,,9EDCw0DqAD</systemId>
      </ser:queryPBIEntitiesNew>
   </soapenv:Body>
</soapenv:Envelope>
''' % (pbi_id)
    else:
        error_log = "Error: paramater worng."
        print error_log
        return False,error_log
    if debug == 1:
        print "[get_ticket_status] params : " + params
    length = len(params)
    if headers is None:
        headers = {'Content-Type': 'text/xml; charset=utf-8', 'Content-Length': length, 'SOAPAction': '"http://tempuri.org/GetListBy"'}
    http_conn = HTTPConnection(host,timeout=600000)
    try:
        urlencode = False
        if urlencode:
            post_data = urllib.urlencode(params)
        else:
            post_data = str(params)
        http_conn.request("POST", url, post_data, headers=headers)

        response = http_conn.getresponse()
        response_status = response.status
        response_content = response.read()
        if debug == 1:
           print "[get_ticket_status] response : " + str(response_content)
        http_conn.close()
        if (response_status  >=300):
            return False,response_content
        else:
            if pbi_id == "":
                rst = response_content.split("<id>")[1].split('</id>')[0].strip()
	    else:
		rst = response_content.split("<en>")[1].split('</en>')[0]
            return True,rst
    except:
        print "".join(traceback.format_exception(*sys.exc_info()))
        return False,{}

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print "Error: Need more paramaters"
        sys.exit(1)
    product_version = ""
    pbi_id = ""
    if len(sys.argv[1]) - len(sys.argv[1].replace(' ','')) != 0:
        product_version = sys.argv[1]
    else:
        pbi_id = sys.argv[1]
    ret,out = get_pbi(product_version, pbi_id)
    print "out = " + out
    sys.exit(0)

